package com.zzyl.serve.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.json.InternalJSONUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.*;
import com.zzyl.serve.mapper.*;
import com.zzyl.serve.util.CodeGenerator;
import com.zzyl.serve.vo.CheckInConfigVo;
import com.zzyl.serve.vo.CheckInDetailVo;
import com.zzyl.serve.vo.CheckInElderVo;
import com.zzyl.serve.vo.ElderFamilyVo;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.serve.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author liuyp
 * @date 2025-08-15
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     * @param checkInDetailVo
     */
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        //1.判断老人是否已登记过并且是"入住"状态
            //获取老人信息
        LambdaQueryWrapper<Elder> wrapper = Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        Elder elder = elderMapper.selectOne(wrapper);
            //判断是否存在
        if(elder!=null && elder.getStatus()==1){
            throw new BaseException("老人已入住！不能重复申请");
        }
        //2.修改床位状态为已入住
        bedMapper.updateStatus(1, checkInConfigDto.getBedId());
        //3.新增或修改老人信息
        Elder newElder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,newElder);
        newElder.setStatus(1);
        newElder.setBedId(checkInConfigDto.getBedId());
        Bed bed = bedMapper.selectBedById(checkInConfigDto.getBedId());
        newElder.setBedNumber(bed.getBedNumber());
            //如果存在执行修改，不存在执行新增
        if(elder==null){
            elderMapper.insert(newElder);
        }else{
            newElder.setId(elder.getId());
            elderMapper.updateById(newElder);
        }
        //4.新增入住信息（家属信息在remark）
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(newElder.getId());
        checkIn.setElderName(newElder.getName());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());

            //插入床位号码
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        save(checkIn);
        //5.新增入住配置信息
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
        //6.保存合同表
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setElderId(newElder.getId().intValue());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(newElder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        LocalDateTime now = LocalDateTime.now();
        if(now.isBefore(checkInConfigDto.getStartDate()) || now.isAfter(checkInConfigDto.getEndDate())){
            contract.setStatus(0);
        }else{
            contract.setStatus(1);
        }
        contractMapper.insert(contract);
    }

    @Override
    public CheckInDetailVo checkInDetail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1.从各个表中获取数据
        CheckIn checkIn = getById(id);
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        LambdaQueryWrapper<CheckInConfig> checkInConfigWrapper = Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigWrapper);
        LambdaQueryWrapper<Contract> contractWrapper = Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, checkIn.getElderId());
        Contract contract = contractMapper.selectOne(contractWrapper);
        //2.封装成CheckInDetailVo
            //2.1封装checkInElderVo
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
            //  计算成age再封装
        LocalDate birth = LocalDate.parse(elder.getBirthday());
        LocalDate now = LocalDate.now();
        int age = birth.until(now).getYears();
        checkInElderVo.setAge(age);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
            //2.2封装elderFamilyVoList
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
            //2.3封装checkInConfigVo对象
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
            //2.4封装contract对象
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
